package com.shengwei.truck.driver.utils;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.graphics.drawable.RoundedBitmapDrawable;
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.bumptech.glide.request.target.Target;
import com.shengwei.truck.driver.R;
import com.shengwei.truck.driver.bean.MyConstant;

import java.io.File;
import java.lang.ref.WeakReference;
import java.text.DecimalFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * 工具类，封装了一些常用函数
 */
public class CommonUtil {
    private static final DecimalFormat DF = new DecimalFormat("######0.00");
    public static final double DISTANCE = 0.0001;
    private static String TAG = "CommonUtil";
    public static final int MILLIS = 0; //毫秒
    public static final int SECOND = 1; //秒

    public static InputFilter newFilter(final Context context) {
        InputFilter inputFilter = new InputFilter() {
            Pattern emoji = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]|[\ud800\udc00-\udbff\udfff\ud800-\udfff]", Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);

            @Override
            public CharSequence filter(CharSequence charSequence, int i, int i1, Spanned spanned, int i2, int i3) {
                Matcher matcher = emoji.matcher(charSequence);
                if (!matcher.find()) {
                    return null;
                } else {
                    Toast.makeText(context, "非法字符", Toast.LENGTH_SHORT).show();
                    return "";
                }
            }
        };
        return inputFilter;
    }

    /**
     * 获取当前APP的进程名称
     *
     * @param context
     * @return
     */
    public static String getCurProcessName(Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : activityManager.getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return "";
    }

    /**
     * 车牌号格式校验
     * @param vehicleNumber
     * @return
     */
    public static  boolean isVehicleNumber(String vehicleNumber){
        boolean result = false;
        if(vehicleNumber.length() == 7){
            String express = "^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$";
            Pattern p = Pattern.compile(express);
            Matcher m = p.matcher(vehicleNumber);
            return m.matches();
        }
        return  result;
    }

    /**
     * Glide加载圆形图片从网络
     *
     * @param imgUrl
     * @param imv
     */
    static public void loadRoundPic(String imgUrl, ImageView imv, Context context) {
        if(!TextUtils.isEmpty(imgUrl)){
            RequestOptions requestOptions = new RequestOptions();
            requestOptions.error(R.drawable.login_head);
            requestOptions.placeholder(R.drawable.login_head);
            Glide.with(context).asBitmap().load(imgUrl)
                    .into(new BitmapImageViewTarget(imv) {
                        @Override
                        protected void setResource(Bitmap resource) {
                            if(resource == null){
                                imv.setImageResource(R.drawable.login_head);
                            }else{
                                RoundedBitmapDrawable circularBitmapDrawable = RoundedBitmapDrawableFactory.create(context.getResources(), resource);
                                circularBitmapDrawable.setCircular(true);
                                imv.setImageDrawable(circularBitmapDrawable);
                            }
                        }
                    });
        }else{
            imv.setImageResource(R.drawable.login_head);
        }

    }

    /**
     * Glide加载圆形图片从文件
     *
     * @param imgFile
     * @param imv
     */
    static public void loadRoundPic(File imgFile, ImageView imv, Context context) {
        if(imgFile != null){
            RequestOptions requestOptions = new RequestOptions();
            requestOptions.error(R.drawable.login_head);
            requestOptions.placeholder(R.drawable.login_head);

            Glide.with(context).asBitmap()
                    .load(imgFile)
                    .listener(new RequestListener<Bitmap>() {
                        @Override
                        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
                            return false;
                        }
                    })
                    .into(new BitmapImageViewTarget(imv) {
                        @Override
                        protected void setResource(Bitmap resource) {
                            if(resource == null){
                                imv.setImageResource(R.drawable.login_head);
                            }else{
                                RoundedBitmapDrawable circularBitmapDrawable = RoundedBitmapDrawableFactory.create(context.getResources(), resource);
                                circularBitmapDrawable.setCircular(true);
                                imv.setImageDrawable(circularBitmapDrawable);
                            }
                        }
                    });
        }else{
            imv.setImageResource(R.drawable.login_head);
        }
    }

    /**
     * 检测当的网络（WLAN、3G/2G）状态
     *
     * @param context Context
     * @return true 表示网络可用
     */
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (info != null && info.isConnected()) {
                // 当前网络是连接的
                if (info.getState() == NetworkInfo.State.CONNECTED) {
                    // 当前所连接的网络可用
                    return true;
                }
            }
        }
        return false;
    }



    /**
     * 校验double数值是否为0
     *
     * @return
     */
    public static boolean isEqualToZero(double value) {
        return Math.abs(value - 0.0) < 0.01 ? true : false;
    }

    /**
     * 经纬度是否为(0,0)点
     *
     * @param latitude  纬度
     * @param longitude 经度
     * @return
     */
    public static boolean isZeroPoint(double latitude, double longitude) {
        return isEqualToZero(latitude) && isEqualToZero(longitude);
    }

    /**
     * 将浮点数保留2位小数
     *
     * @param doubleValue
     * @return
     */
    public static final String formatDouble(double doubleValue) {
        return DF.format(doubleValue);
    }


    /**
     * 获取 APP版本名称versionName
     */
    public static String getVersionName(Context context) {
        PackageManager packageManager = context.getPackageManager();

        try {
            PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            return packInfo.versionName;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取 APP版本ID号： versionCode
     */
    public static int getVersionCode(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            return packInfo.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1;
    }

    /**
     * 安装APK
     *
     * @param file：要安装的APP安装包文件
     */
    public static void install(File file, Context context) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        context.startActivity(intent);
        return;
    }


    /**
     * 检查输入的人名
     *
     * @param personName：          人的真实姓名
     * @param weakReferenceContext
     * @return
     */
    public static boolean checkPersonName(String personName, WeakReference<Context> weakReferenceContext) {
        Context contextWeakReference = weakReferenceContext.get();
        if (TextUtils.isEmpty(personName) && contextWeakReference != null) {
            Toast.makeText(weakReferenceContext.get(), R.string.person_name_emptey, Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    /**
     * 检查身份证号格式是否合法
     *
     * @param identifyNum：         待检查的身份证号
     * @param weakReferenceContext 页面上下文包裹成弱引用，防止内存泄露
     * @return ture合法，false不合法
     */
    public static boolean checkIdentify(String identifyNum, WeakReference<Context> weakReferenceContext) {
        Context contextWeakReference = weakReferenceContext.get();

        if (TextUtils.isEmpty(identifyNum) && contextWeakReference != null) {
            Toast.makeText(contextWeakReference, R.string.identify_empty, Toast.LENGTH_SHORT).show();
            return false;
        }
        boolean isValid = IdentifyValidate.isValid(identifyNum);

        if (!isValid) {
            Toast.makeText(contextWeakReference, R.string.identify_incorrect, Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    /**
     * 检查用户名
     *
     * @param username             待检查的用户名
     * @param weakReferenceContext
     * @return
     */
    public static boolean checkUserName(String username, WeakReference<Context> weakReferenceContext) {
        Context contextWeakReference = weakReferenceContext.get();
        //用户名
        if (TextUtils.isEmpty(username) && contextWeakReference != null) {
            Toast.makeText(contextWeakReference, R.string.username_empty, Toast.LENGTH_SHORT).show();
            return false;
        }

        //是否包含非数字
        String regExpNotNum = "[^0-9]+";
        Pattern notNumPattern = Pattern.compile(regExpNotNum);
        Matcher notNumMatcher = notNumPattern.matcher(username);
        boolean isContainNotNum = notNumMatcher.find();

        //用户名至少3个字符，且不能是纯数字
        if (username.length() < 3 && contextWeakReference != null) {
            Toast.makeText(contextWeakReference, R.string.username_min_len, Toast.LENGTH_SHORT).show();
            return false;
        } else {
            //不能是纯数字
            if (!isContainNotNum && contextWeakReference != null) {
                Toast.makeText(contextWeakReference, R.string.ban_pure_num, Toast.LENGTH_SHORT).show();
                return false;
            }
        }
        return true;
    }

    /**
     * 检查密码
     *
     * @param password             待检查的密码
     * @param weakReferenceContext
     * @param type                 密码类型，0表示密码，3表示确认密码
     * @return
     */
    public static boolean checkPassword(String password, WeakReference<Context> weakReferenceContext, int type) {
        Context contextWeakReference = weakReferenceContext.get();

        //密码长度
        boolean isCorrectPwd = CommonUtil.checkPwdLength(password, contextWeakReference, type);

        if (!isCorrectPwd && contextWeakReference != null) {
            return false;
        }
        return true;
    }


    /**
     * 验证密码 格式
     *
     * @param ：输入的密码串
     * @param context
     * @param type：密码串类型
     * @return
     */
    public static boolean checkPwdLength(String pwd, Context context, int type) {
        String tip = "密码";
        switch (type) {
            case 0:
                tip = "密码";
                break;
            case 1:
                tip = "原密码";
                break;
            case 2:
                tip = "新密码";
                break;
            case 3:
                tip = "确认密码";
                break;
            default:
                tip = "密码";
                break;
        }

        if (TextUtils.isEmpty(pwd) && context != null) {
            WeakReference<Context> contextWeakReference = new WeakReference<>(context);
            MyToast.showToastCenter(contextWeakReference,tip + "不能为空",Toast.LENGTH_SHORT,true);
            return false;
        }
        if (pwd.length() < 6 && context != null) {
            WeakReference<Context> contextWeakReference = new WeakReference<>(context);
            MyToast.showToastCenter(contextWeakReference,tip + "不能小于6位",Toast.LENGTH_SHORT,true);
            return false;
        } else if (pwd.length() > 16 && context != null) {
            WeakReference<Context> contextWeakReference = new WeakReference<>(context);
            MyToast.showToastCenter(contextWeakReference,tip + "不能大于16位",Toast.LENGTH_SHORT,true);
            return false;
        }
        return true;
    }

    /**
     * 替换字符串中的占位变量
     *
     * @param str    占位字符串,如"您的被监护对象{0},佩戴的{1}（设备编号：{2}）{3}"
     * @param params 各占位的值
     * @return
     */
    public static String repString(String str, String... params) {
        for (int i = 0; i < params.length; i++) {
            str = str.replace("{" + i + "}", params[i] == null ? null : params[i]);
        }
        return str;
    }

    //检查手机号START

    /**
     * 大陆号码或香港号码都可以
     *
     * @param mobile:              手机号
     * @param weakReferenceContext 上下文
     * @return boolean 为true手机号格式正确，false不正确
     * @throws PatternSyntaxException
     */
    public static boolean checkMobile(String mobile, WeakReference<Context> weakReferenceContext, boolean isTipError) {
        Context contextWeakReference = weakReferenceContext.get();

        if (TextUtils.isEmpty(mobile)) {

            if (contextWeakReference != null) {
                if (isTipError) {
                    String mobileEmpty = contextWeakReference.getResources().getString(R.string.mobile_empty);
                    MyToast.showToastCenter(weakReferenceContext,mobileEmpty,Toast.LENGTH_SHORT,true);
                }
                return false;
            }
        }

        boolean isCorrectMobile = isChinaPhoneLegal(mobile) || isHKPhoneLegal(mobile);

        if (!isCorrectMobile) {
            if (isTipError && contextWeakReference != null) {
                String mobileInvalid = contextWeakReference.getResources().getString(R.string.mobile_incorrect);
                MyToast.showToastCenter(weakReferenceContext,mobileInvalid,Toast.LENGTH_SHORT,true);
                return false;
            }
        }
        return true;
    }


    /**
     * 大陆手机号码11位数，匹配格式：前三位固定格式+后8位任意数
     * 此方法中前三位格式有：
     * 13+任意数
     * 145,147,149
     * 15+除4的任意数(不要写^4，这样的话字母也会被认为是正确的)
     * 166
     * 17+3,5,6,7,8
     * 18+任意数
     * 198,199
     *
     * @param str
     * @return 正确返回true
     * @throws PatternSyntaxException
     */
    public static boolean isChinaPhoneLegal(String str) throws PatternSyntaxException {
        // ^ 匹配输入字符串开始的位置
        // \d 匹配一个或多个数字，其中 \ 要转义，所以是 \\d
        // $ 匹配输入字符串结尾的位置
        String regExp = "^((13[0-9])|(14[5,7,9])|(15[0-3,5-9])|(166)|(17[3,5,6,7,8])" +
                "|(18[0-9])|(19[8,9]))\\d{8}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }

    /**
     * 香港手机号码8位数，5|6|8|9开头+7位任意数
     *
     * @param str
     * @return 正确返回true
     * @throws PatternSyntaxException
     */
    public static boolean isHKPhoneLegal(String str) throws PatternSyntaxException {
        // ^ 匹配输入字符串开始的位置
        // \d 匹配一个或多个数字，其中 \ 要转义，所以是 \\d
        // $ 匹配输入字符串结尾的位置
        String regExp = "^(5|6|8|9)\\d{7}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }
    //检查手机号END

    public static String getStateByCode(int statusCode,WeakReference<Context> contextWeakReference) {
        String stateText = "";
        Context context = contextWeakReference.get();
        switch (statusCode) {
            case 0:
                if(context != null){
                    stateText = context.getResources().getString(R.string.qr_refresh_please);
                }
                else{
                    stateText = "扫码提货";
                }
                break;
            case 1:
                stateText = "扫码提货";  //已接单
                break;
            case 2:
                stateText = "已提货";
                break;
            case 3:
            case 4:
            case 5:
                stateText = "完成";  //已完成
                break;
            case 6:
                stateText = "已取消";
                break;
            default:
                stateText = "未知";

        }
        return stateText;
    }

    /**
     * dp转px
     *
     * @param context
     * @param dips
     * @return
     */
    public static int dipsToPixels(Context context, float dips) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dips * scale + 0.5f);
    }


    /**
     * 得到手机品牌及返回品牌ID  OnePlus
     */
    static public int getMobileBrandId() {
        int brandId = -1;
        String brand = (android.os.Build.BRAND);
        String lowerLetterBrand = brand.toLowerCase();
        Log.i("brand", "brand=" + lowerLetterBrand);
        switch (lowerLetterBrand) {
            case MyConstant.HUAWEI:
                brandId = 1;
                break;
            case MyConstant.MI:
                brandId = 2;
                break;
            case MyConstant.OPPO:
                brandId = 3;
                break;
            case MyConstant.VIVO:
                brandId = 4;
                break;
            case MyConstant.HUAWEI_HONOR:  //华为荣耀
                brandId = 1;
                break;
            case MyConstant.OPPO_ColorOS:  //oppo
                brandId = 3;
                break;
        }
        return brandId;
    }
}
